﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Reactive.Linq;
using MiscUtil;
using TlvLib.SiChuan.Packet;
using System.Net;

namespace TlvLib.SiChuan
{
    class RegistrationResult
    {
        public Exception Error;
        public RegistrationReply Reply;
        public TcpClient Client;
    }

    class Register
    {

        public RegistrationResult RegistCore(IPEndPoint endpoint, bool isSecond)
        {
            var client = new TcpClient();
            RegistrationResult res = null;
            try
            {
                client.Connect((IPEndPoint)endpoint);

                var packet = TvPacketFactory.CreateRegistrationPacket();
                Observable.Timer(TimeSpan.FromSeconds(10)).Subscribe(l =>
                                                                         {
                                                                             if (!client.Connected)
                                                                             {
                                                                                 client.Close();
                                                                             }
                                                                         });

                TlvWriter.Write(client.GetStream(), packet);

                var replyBuf = TlvReader.Read(client.GetStream());
                Packet.RegistrationReply reply;
                if (Unpacker.RegistrationUnpacker.TryUnpack(replyBuf, out reply))
                {
                    res = new RegistrationResult() { Error = null, Reply = reply, Client = client };
                }
                else
                {
                    res = new RegistrationResult() { Error = new Exception("invalid reply format") };
                }
            }
            catch (System.IO.EndOfStreamException ex)
            {
                res = new RegistrationResult() { Error = ex };
            }
            finally
            {
                if (client.Connected && !isSecond)
                {
                    client.Close();
                }
            }

            return res;

        }
    }
}
